#! /usr/local/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import re
import time
from sheepomatic import Sheep
import sheepomatic
from sheepomatic_io import Csv_file

from gmail_sender import Gmail_sender

class Sheep_mailer:
   @classmethod
   def get_sheep_info(cls,sheep,conf_tuples):
      sheep_info = ""
      for attr_name,attr_meaning in conf_tuples:
         sheep_info += attr_meaning+": "+sheep.attr(attr_name)+"\n"
      return sheep_info

   @classmethod
   def get_shepherd2sheep_hash(cls,sheep_list,pivot_attr):
      shepherd2sheep_hash = {}
      for sheep in sheep_list:
         shepherd_mail = sheep.attr(pivot_attr)
         if shepherd_mail not in shepherd2sheep_hash:
            shepherd2sheep_hash[shepherd_mail] = []
         shepherd2sheep_hash[shepherd_mail].append(sheep)
      return shepherd2sheep_hash

   @classmethod
   def get_pivot_attr(cls,conf_tuples):
      pivot_attr = None
      for attr_name,attr_meaning in conf_tuples:
         if attr_meaning == "pivot":
            pivot_attr = attr_name
      if pivot_attr == None:
         print >> sys.stderr, "No pivot in conf file!"
         sys.exit(1)
      else:
         conf_tuples.remove((pivot_attr,"pivot"))
         return pivot_attr

   @classmethod
   def get_shepherd2full_addr_hash(cls,sheep_list,pivot_attr,\
                                   shepherd_name_attr):
      shepherd2full_addr_hash = {}
      for sheep in sheep_list:
         shepherd2full_addr_hash[sheep.attr(pivot_attr)] =\
               sheep.attr(shepherd_name_attr)+" <"+sheep.attr(pivot_attr)+">"
      return shepherd2full_addr_hash

   @classmethod
   def get_shepherd_name_attr(cls,conf_tuples):
      tutor_name_attr = None
      for attr_name,attr_meaning in conf_tuples:
         if attr_meaning == "tutor_name":
            tutor_name_attr = attr_name
      if tutor_name_attr == None:
         print >> sys.stderr, "No tutor_name in conf file!"
         sys.exit(1)
      else:
         conf_tuples.remove((tutor_name_attr,"tutor_name"))
         return tutor_name_attr

   @classmethod
   def compile_mail(cls,mail_template_file,sheep_list,conf_tuples):
      # get sheep info block
      all_sheep_info = "\n".join(\
               map(lambda sheep: cls.get_sheep_info(sheep,conf_tuples), sheep_list))
      # read template
      f = open(mail_template_file, 'r')
      mail = ""
      for line in f.readlines():
         mail+=line
      f.close()
      mail = re.sub('\[% students %\]', all_sheep_info, mail)
      return mail

   @classmethod
   def read_sent_addrs(cls,sent_addr_log):
      sent_addrs_set = set([])
      # read addrs
      f = open(sent_addr_log, 'r')
      for line in f.readlines():
         line = line.strip()
         sent_addrs_set.add(line)
      f.close()
      return sent_addrs_set

def main(args):
   sheep_filename = args[0]
   attr_conf_filename = args[1]
   mail_template_file = args[2]
   sent_addr_log = args[3]
   # read sheep (with shepherd annotation)
   sheep_list = Csv_file.read_sheep_file(sheep_filename)
   # read conf with transformation of labels (+pivot)
   conf_tuples = sheepomatic.conf_file2tuples(attr_conf_filename)
   pivot_attr = Sheep_mailer.get_pivot_attr(conf_tuples)
   shepherd_name_attr = Sheep_mailer.get_shepherd_name_attr(conf_tuples)
   #
   shepherd2sheep_hash = Sheep_mailer.get_shepherd2sheep_hash(sheep_list,pivot_attr)
   shepherd2full_addr_hash = Sheep_mailer.get_shepherd2full_addr_hash(\
                                 sheep_list,pivot_attr,shepherd_name_attr)
   sent_addrs_set = Sheep_mailer.read_sent_addrs(sent_addr_log)
   #
   sender = Gmail_sender()
   print >> sys.stderr, "Sending emails,", len(shepherd2sheep_hash), "to send."
   for shepherd in shepherd2sheep_hash:
      # prepare information
      sys.stderr.write("   "+shepherd+" [" + shepherd2full_addr_hash[shepherd] + "]")
      curr_sheep_list = shepherd2sheep_hash[shepherd]
      full_shepherd_addr = shepherd2full_addr_hash[shepherd]
      if shepherd in sent_addrs_set:
         sys.stderr.write(" SKIPPED\n") 
      else:
         # send the mail
         time.sleep(20)
         message_body = Sheep_mailer.compile_mail(mail_template_file,\
                                                  curr_sheep_list,conf_tuples)
         sender.send_tutoring_message(full_shepherd_addr.decode('utf-8'),
                                      "Tutoring podzim 2012", message_body.decode('utf-8'))
         
         logfile = open(sent_addr_log,'a')
         print >> logfile, shepherd
         sys.stderr.write(" ok\n") 

if __name__ == '__main__':
    args = sys.argv[1:]
    main(args)

